/**
 * Created by Administrator on 2017/7/29.
 */

//百度统计
var _hmt = _hmt || [];
(function() {
    var hm = document.createElement("script");
    hm.src = "https://hm.baidu.com/hm.js?c480ee3eba2fe8c48db50108afb79db2";
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(hm, s);
})();

//百度统计


//返回当前页面名
function pageName()
{
    var a = location.href;
    var b = a.split("/");
    var c = b.slice(b.length-1, b.length).toString(String).split(".");
    var d=c.slice(0, 1).toString();
    return d;
}
//监听用户是否登入

function islogin() {
    var aircraft=localStorage.getItem('aircraft');
    if(notNull(aircraft)){
        return true
    } else {
        return false
    }
}


try{

    var citysearch = new AMap.CitySearch();
    //自动获取用户IP，返回当前城市
    citysearch.getLocalCity(function (status, result) {
        if (status === 'complete' && result.info === 'OK') {
            if (result && result.city && result.bounds) {
                var GetUserLocation = result.city,
                    GetUserLocationcode = result.adcode;
                sessionStorage.setItem('autolocationct', GetUserLocation);
                sessionStorage.setItem('autolocationcode', GetUserLocationcode);

                if(pageName()=='index'){

                    if(islogin()){
                        try {
                            var user_code=getUserInfo().region.code;
                            var user_cityName=getUserInfo().region.name;

                            sessionStorage.setItem('locationcode',user_code);       //更新来自登入用户的code

                            $(".locationCity i").text(user_cityName);

                        }
                        catch(e){
                            $(".locationCity i").text('全国');
                        }

                    }else {
                        var userlocation = sessionStorage.getItem('locationcodenameindex');  //手动定位城市

                        var autolocationct = sessionStorage.getItem('autolocationct');      //自动定位地址

                        if(notNull(userlocation)){
                            $(".locationCity i").text(userlocation);

                        }else {

                            if(notNull(autolocationct)){
                                $(".locationCity i").text(autolocationct);

                            }else {
                                $(".locationCity i").text('全国');

                            }
                        }
                    }

                }

            }
        } else {
            $(".locationCity i").text('全国');
        }

    });



}
catch (e) {
    console.log('引用定位失败')

}



;(function(){
    var zIndex = 100000;
    var jqueryAlert = function(opts){
        // 设置默认参数
        var opt = {
            'style'        : 'wap', //移动端和PC端
            'title'        : '',    //标题
            'icon'         : '',
            'content'      : '',	//内容
            'contentTextAlign' : 'center', //内容对齐方式
            'width'        : 'auto', //宽度
            'height'       : 'auto', //高度
            'minWidth'     : '0', //最小宽度
            "className"    : '', //添加类名
            'position'     : 'fixed', //定位方式
            'animateType'  : 'scale',
            'modal'        : false, //是否存在蒙层
            'isModalClose' : false, //点击蒙层是否关闭
            'bodyScroll'   : false, //是否关闭body的滚动条
            'closeTime'    : 3000, //当没有按钮时关闭时间
            "buttons"      : {}, //按钮对象</pre>
        };

        // 参数合并
        var option = $.extend({},opt,opts);

        var dialog = {

        };

        dialog.time = 450;//动画关闭时间
        dialog.init = function(){
            dialog.framework();
        };

        // 事件处理
        function IsPC() {
            var userAgentInfo = navigator.userAgent;
            var Agents = ["Android", "iPhone",
                "SymbianOS", "Windows Phone",
                "iPad", "iPod"];
            var flag = true;
            for (var v = 0; v < Agents.length; v++) {
                if (userAgentInfo.indexOf(Agents[v]) > 0) {
                    flag = false;
                    break;
                }
            }
            return flag;
        }
        var isHaveTouch = IsPC();
        if(isHaveTouch){
            dialog.event = 'click';
        }else{
            dialog.event = 'touchstart';
        };

        var $modal = $("<div class='alert-modal'>");
        var $container = $("<div class='alert-container animated'>");
        var $title = $("<div class='alert-title'>"+option.title+"</div>");
        var $content = $("<div class='alert-content'>");
        var $buttonBox = $("<div class='alert-btn-box'>");
        var $closeBtn = $("<div class='alert-btn-close'>×</div>");

        if(!!option.content[0] && (1 == option.content[0].nodeType)){
            var $newContent = option.content.clone();
            $content.append($newContent)
        }else{
            $content.html(option.content);
        };

        dialog.framework = function(){

            dialog.buttons = [];
            for(var key in option.buttons){
                dialog.buttons.push(key);
            };
            dialog.buttonsLength = dialog.buttons.length;

            $container.append($title)
                .append($content);

            if(option.style == 'pc'){
                $container.append($closeBtn).addClass('pcAlert');
            };

            if(option.modal || option.modal == 'true'){
                $('body').append($modal);
                option.bodyScroll && $('body').css('overflow','hidden');
            };
            $('body').append($container);

            // 设置内容的对齐方式
            $content.css({
                'text-align' : option.contentTextAlign
            });

            if(parseInt(option.minWidth) > parseInt($container.css('width'))){
                option.width = option.minWidth;
            };

            $modal.css('position',option.position);
            $modal.css('z-index',zIndex);

            ++zIndex;

            if(option.position == 'fixed'){
                $container.css({
                    'position' : option.position,
                    'left'     : '50%',
                    'top'      : '50%',
                    'z-index'  : zIndex,
                });
            };
            if(option.position == 'absolute'){
                $container.css({
                    'position' : option.position,
                    'left'     : $(window).width()/2,
                    'top'      : $(window).height()/2 + $(window).scrollTop(),
                    'z-index'  : zIndex,
                });
            };

            $container.css('width',option.width);
            $container.css('height',option.height);

            if(option.width == 'auto'){
                $container.css('width',$container[0].clientWidth + 10);
            };

            if(parseInt($(window).height()) <=  parseInt($container.css('height'))){
                $container.css('height',$(window).height());
            };

            // 设置class
            (!!option.className) && $container.addClass(option.className);

            // 设置button内容
            for(var key in option.buttons){

                var $button = $("<p class='alert-btn-p'>"+ key +"</p>");
                if(option.style != 'pc'){
                    $button.css({
                        'width' : Math.floor(($container[0].clientWidth) / dialog.buttonsLength),
                    })
                };
                //绑定点击后的事件
                $button.bind(dialog.event,option.buttons[key]);
                $buttonBox.append($button);

            };

            if(dialog.buttonsLength > 0){
                $container.append($buttonBox);
                $content.css('padding-bottom','46px');
                //处理IE下滚动条的问题
                if (window.navigator.userAgent.indexOf("MSIE")>=1) {
                    if($content[0].scrollHeight > $content[0].clientHeight){
                        $content.css('height',parseInt($content.css('height')) - 46 );
                    }
                };
            };

            if(option.title != ''){
                $content.css('padding-top','42px');
            };

            if(dialog.buttonsLength <= 0 && option.title == ''){
                $container.addClass('alert-container-black');
                if(!!option.icon){
                    $content.css({
                        'padding-top' : '45px',
                        'background'  : 'url('+option.icon+') no-repeat center 5px',
                        'background-size' : 'auto 40px'
                    });
                };
            };

            // 设置定位
            $container.css({
                'margin-left' : -parseInt($container.css('width'))/2,
                'margin-top' : -parseInt($container.css('height'))/2,
            });

            if(option.animateType == 'scale'){
                $container.addClass('bounceIn');
            };

            if(option.animateType == 'linear'){
                $container.addClass('linearTop');
            };

            isSelfClose();

        };

        // 判断是否满足自动关闭的条件
        function isSelfClose(){
            if(dialog.buttonsLength <= 0 && option.style != 'pc'){
                setTimeout(function(){
                    $container.fadeOut(300);
                    $modal.fadeOut(300);
                    option.bodyScroll && $('body').css('overflow','auto');
                },option.closeTime)
            };
        };

        dialog.toggleAnimate = function(){
            if(option.animateType == 'scale'){
                return $container.removeClass('bounceIn').addClass('bounceOut');
            }else if(option.animateType == 'linear'){
                return $container.removeClass('linearTop').addClass('linearBottom');
            }else{
                return $container;
            };
        };

        dialog.close = function(){
            dialog.toggleAnimate().fadeOut(dialog.time);
            $modal.fadeOut(dialog.time);
            option.bodyScroll && $('body').css('overflow','auto');
        };

        option.style == 'pc' && $closeBtn.bind(dialog.event,dialog.close);
        option.isModalClose && $modal.bind(dialog.event,dialog.close);

        dialog.destroy = function(){
            dialog.toggleAnimate().fadeOut(dialog.time);
            setTimeout(function(){
                $container.remove();
                $modal.remove();
                option.bodyScroll && $('body').css('overflow','auto');
            },dialog.time)
        };
        dialog.show = function(){

            $modal.css('z-index',zIndex);

            ++zIndex;

            $container.css({
                'z-index'  : zIndex,
            });

            if(option.animateType == 'scale'){
                $container.fadeIn().removeClass('bounceOut').addClass('bounceIn');
            }else if(option.animateType == 'linear'){
                $container.fadeIn().removeClass('linearBottom').addClass('linearTop');
            }else{
                $container.fadeIn()
            };

            if(option.position == 'absolute'){
                $container.css({
                    'top'      : $(window).height()/2 + $(window).scrollTop(),
                })
            };

            $modal.fadeIn();
            option.bodyScroll && option.modal && $('body').css('overflow','hidden');
            isSelfClose();
        };

        dialog.init();

        return dialog

    }
    if (typeof module !== 'undefined' && typeof exports === 'object') {
        module.exports = jqueryAlert;
    } else if (typeof define === 'function' && (define.amd || define.cmd)) {
        define(function() { return jqueryAlert; });
    } else {
        this.jqueryAlert = jqueryAlert;
    }
}).call(function() {
    return this || (typeof window !== 'undefined' ? window : global);
}());





function isResponseSuccess(response ,data){
    if(response==='getdata'){  return data.data.pageDate}
    else if(response==='msg'){  return data.msg}
    else if(response==='data'){  return data.data}
    else if(response==='success'){  return data.success}
    else if(response==='errorCode'){  return data.errorCode}
    else if(response==='token'){ return data.token}
    else{
        return '';
    }
}


//获取平台信息
function getPlatform() {
    var fromUrl=navigator.userAgent,
        a=fromUrl.indexOf('('),
        b=fromUrl.indexOf(')'),
        platform=fromUrl.slice(a,b+1);
    console.log(platform);
    return platform;
}
//调整图片显示方式
function changeImg(){
    var _imga=$('.list_a img');
    _imga.load(function () {
        var Imgheight=$(this).height();
        var ImgWidth=$(this).width();
        if(Imgheight>ImgWidth){
            $(this).parent().addClass('list_c').removeClass('list_a');
        }
    });

    var _imgb=$('.list_b img');
    _imgb.load(function () {
        var Imgheight=$(this).height();
        var ImgWidth=$(this).width();
        if(Imgheight>ImgWidth){
            $(this).addClass('forWidth')
        }else {
            $(this).addClass('forHeight')
        }
    })


}




// //电脑兼容
// if (/Android|webOS|iPhone|iPod|BlackBerry/i.test(navigator.userAgent)) {
//     document.documentElement.style.fontSize = document.documentElement.clientWidth / 750 * 100 + 'px';
//     $('.appimg').hide();
//     $('.saoyisao').hide();
//     /*   document.title='借贷家';*/
//
// } else {
//     var windowHeight=window.screen.height;
//     $('html').css({'width':"375", 'margin':'0 auto','font-size':'50px'});
//     $('header').css({'width':'375','margin':'0 auto'});
//     $('footer').css({'width':'375','margin':'0 auto','bottom':'282'});
//     $('#chooseMassage').css({'width':'375','margin':'0 auto'});
//     $('.top-search').css({'width':'375','margin':'0 auto','left': 'auto'});
//     $('#loansGroupSearchNav').css({'width':'375','margin':'0 auto','left': 'auto'});
//     $('#loansGroupSearch_group_or_post_Nav').css({'width':'375','margin':'0 auto','left': 'auto'});
//     $('.commentbox').css({'width':'375','margin':'0 auto','bottom':'282'});
//     $('nav').css({'width':'375','margin':'0 auto'});
//     $('#meheader').css({'padding':'0'});
//     $('#locationinput').css({'width':'375','padding':'0'});
//     $('select').css({'margin':'0'});
//
//     $('.down1').remove();
//
//     $('#loansMain').css({'padding-bottom':'1.5rem'});
//     $('#meFooter').css({'position':"relative"});
//     $('#suggestionup').css({'position':"relative"});
//     $('#imgBox').css({'width':'375'});
//     if(pageName()=='index'){
//         $('<img>', {
//             src: 'publicImg/app.png',
//             class: 'appimg'
//
//         }).appendTo('body');
//         $('<img>', {
//             src: 'publicImg/web.png',
//             class: 'saoyisao'
//
//         }).appendTo('body');
//
//
//
//
//     }else {
//         $('<img>', {
//             src: '../publicImg/app.png',
//             class: 'appimg'
//
//         }).appendTo('body');
//         $('<img>', {
//             src: '../publicImg/web.png',
//             class: 'saoyisao'
//
//         }).appendTo('body');
//     }
//
//
// }



//判断是否是管理员；
function set_roles(){
    var userinfo=getUserInfo();
    var  roles=userinfo.roles;
    if(roles=='管理员'){
        return true
    }else {
        return false
    }
}

//提示对象容器
var M = {};
///发帖子未登入提示
function notLogin(form){
    if(M.Login){
        return M.Login.show();
    }
    M.Login = jqueryAlert({
        'title'   : '借贷家提示',
        'content' : '对不起，您还未登入需要登入吗？',
        'modal'   : true,
        'buttons' :{
            '取消' : function(){
                M.Login.close();
            },
            '登录' : function(){
                M.Login.close();
                var url='login.html';
                switchLocation(url)
            }
        }
    })
}



//默认提示
function defaultHint(msg){
    var M={};
    if(M.Hint){
        return M.Hint.show();
    }
    M.Hint = jqueryAlert({
        'content' : msg,
        'closeTime' : 1500,
    })
}


///未设置昵称提示 (gotofb)
function nickName() {
    if(M.nickname){
        return M.nickname.show();
    }
    M.nickname=jqueryAlert({
        "title":'借贷家提示',
        "content":'对不起，您还没有昵称哦！去设置吧!',
        'modal'   : true,
        'buttons' :{
            '不用了' : function(){
                M.nickname.close();
            },
            '去设置' : function(){
                M.nickname.close();
                var url='addnameimg.html?gotofb=sendmessage';
                switchLocation(url)
            }
        }
    })
}


//存储userInfo
var userInfoOff=false;
function setUserInfo(user) {
    console.log(user);
    user=JSON.stringify(user);
    if(notNull(user)){
        user=Base64.encode(user);
        var time = new Date();        //获取当前日(1-31)
        localStorage.setItem('time', time.getDate());
    }
    localStorage.setItem('user',user);
    userInfoOff=true;
}
//获取userInfo

function getUserInfo() {
    var user=localStorage.getItem('user');


    if(notNull(user)){
        user=Base64.decode(user);
        user=JSON.parse(user);
    }

    if(user==null){
        user='';
    }
    return user
}



//存储userComment,跳转到评论页面
function setUserComment(userComment) {
    var userComment=JSON.stringify(userComment);
    if(notNull(userComment)){
        userComment=Base64.encode(userComment);
    }
    sessionStorage.setItem('userComment',userComment);
    var url='sendcomment.html';
    switchLocation(url)
}


//获取userComment
function getUserComment(userComment) {
    var userComment=sessionStorage.getItem('userComment');
    if(notNull(userComment)){
        userComment=Base64.decode(userComment);
    }
    userComment=JSON.parse(userComment);
    if(userComment==null){
        userComment='';
    }
    return userComment
}


//存储session对象
//初始化对象
var SessionObj={};
function setSessionObj(sessionKey,sessionVal){
    var setSessionObj=JSON.stringify(sessionVal);
    if(notNull(setSessionObj)){
        setSessionObj=Base64.encode(setSessionObj);
    }
    sessionStorage.setItem(sessionKey,setSessionObj);
}
//获取session对象
function getSessionObj(sessionKey){
    var sessionVal=sessionStorage.getItem(sessionKey);
    if(notNull(sessionVal)){
        sessionVal=Base64.decode(sessionVal);
    }
    sessionVal=JSON.parse(sessionVal);
    if(sessionVal==null){
        sessionVal='';
    }
    return sessionVal
}




function myBeforeSend(request){
    var token=localStorage.getItem('aircraft');
    if(notNull(token)){
        var aircraft = Base64.decode(token);
        request.setRequestHeader("authorization", aircraft);
    }

}


function ling(data){

    var text = data.responseText.indexOf('令牌');
    console.log(data);

    if (text == '-1') {
        var smg='请求数据失败,请点击返回或者刷新重试！';
        defaultHint(smg);
    } else {


        if(M.tokenShow){
            return M.tokenShow.show();
        }
        M.tokenShow = jqueryAlert({
            'title'   : '借贷家提示',
            'content' : '登入失效请重新登入',
            'modal'   : true,
            'buttons' :{
                '确定' : function(){
                    sessionStorage.clear();
                    localStorage.clear();
                    var url=geturlBase+'login.html';
                    switchLocation(url);
                    M.tokenShow.close();
                }
            }
        })

    }

}



function myUrlNoCache(url) {
    var newUrl='';
    if(url.indexOf('?')>-1){
        newUrl=url+'&seq='+new Date().getTime();
    } else{
        newUrl=url+'?seq='+new Date().getTime();
    }
    return newUrl;
}


function switchLocation(url) {
    window.location.href=myUrlNoCache(url);
}


function myAjaxFunc(obj) {
    obj.beforeSend=myBeforeSend;
    obj.error=ling;
    obj.url=myUrlNoCache(obj.url);

    obj.success=function(data){
        changeCode(data);
        if(notNull(obj.mySuccess))
            obj.mySuccess(data)
    };

    $.ajax(obj);
}

//没有错误提示处理
function myAjaxFuncWithNotErrorCommit(obj) {
    obj.beforeSend=myBeforeSend;
    obj.url=myUrlNoCache(obj.url);
    obj.success=function(data){
        changeCode(data);
        if(notNull(obj.mySuccess))
            obj.mySuccess(data)
    };
    $.ajax(obj);
}

function myAjaxFuncJsonNotchangeToken(obj) {
    obj.beforeSend = myBeforeSend;
    obj.error = ling;
    obj.url = myUrlNoCache(obj.url);
    obj.data = JSON.stringify(obj.data);
    obj.contentType = "application/json";
    obj.success = function (data) {
        if (notNull(obj.mySuccess))
            obj.mySuccess(data)
    };
    $.ajax(obj);
}



//获取当前token解码
function getCurrentToken() {
    var aircraft = localStorage.getItem('aircraft');
    var token = null;
    if (notNull(aircraft)){
        token = Base64.decode(aircraft);
    }
    return token;
}


function changeCode(data){
    var newToken=isResponseSuccess('token' ,data);
    if(notNull(newToken)){

       //更新token和user，并且newToken不为空
        let token = getCurrentToken();

        //验证token是否有更新
        if (newToken != token) {

                //利用新的token去更新user
            $.ajax({
                url: geturluser + 'getUser',
                type: 'post',
                cache: false,
                beforeSend:function (request) {
                    request.setRequestHeader("authorization", newToken);
                },
                success: function (data) {
                    var user = data.data.user;
                    console.log(user);
                    setUserInfo(user);
                    localStorage.setItem('aircraft',Base64.encode(newToken));

                }
            });
        }
    }else {
        localStorage.clear();
    }
}







/*读取地址参数*/

function searchUrl() {
    var URL = window.location.href;
    var name, value;
    var srt = URL.indexOf("?");
    var inner = URL.slice(srt + 1);
    var arr = inner.split("&");
    for (var i = 0; i < arr.length; i++) {
        srt = arr[i].indexOf("=");
        if (srt > 0) {
            name = arr[i].substring(0, srt);
            value = arr[i].substr(srt + 1);
            this[name] = value;
        }
    }
}
/**/

/*正则验证*/
var tellnumber = new RegExp(/^1[3|4|5|7|8]\d{9}$/)//手机号码
    , numberkey = new RegExp(/^\w{6,18}/)//密码6-18字母数字下划线
    , numberId = new RegExp(/(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/)
    , checkPass = function (tell) {
        if (numberkey.test(tell)) {
            return true
        } else {
            return false
        }
    }
    , verifyTel = function (tel) {
        if (tellnumber.test(tel)) {
            return true
        } else {
            return false
        }
    }
    , checkId = function (tel) {
        if (numberId.test(tel)) {
            return true
        } else {
            return false
        }
    }
    , notNull= function (obj){


        if(obj==='0'){
            return true
        }
        if(obj===0){
            return true
        }


        if (obj===''||obj===null||obj===undefined||obj==='null'||obj==='undefined'){
            return false
        }else {
            return true
        }
    },isNull= function (obj){

        if(obj==='0'){
            return false
        }
        if(obj===0){
            return false
        }
        if(obj===''){
            return true
        }



        if (obj===''||obj==null||obj===undefined||obj==='null'||obj==='undefined'){
            return true;
        }else {
            return false;
        }
    }
    ,html_encode=function(str){
        var s = "";
        if (str.length == 0) return "";
        s = str.replace(/&/g, "&amp;");
        s = s.replace(/</g, "&lt;");
        s = s.replace(/>/g, "&gt;");
        s = s.replace(/ /g, "&nbsp;");
        s = s.replace(/\'/g, "&#39;");
        s = s.replace(/\"/g, "&quot;");
        s = s.replace(/\n/g, "<br/>");
        return s;
    },html_decode=function (str) {
        var s = "";
        if(str.length == 0) return "";
        s = str.replace(/&amp;/g,"&");
        s = s.replace(/&lt;/g,"<");
        s = s.replace(/&gt;/g,">");
        s = s.replace(/&nbsp;/g," ");
        s = s.replace(/&#39;/g,"\'");
        s = s.replace(/&quot;/g,"\"");
        return s;
    }
    , Base64 = {
        _keyStr: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
        encode: function (e) {
            var t = "";
            var n, r, i, s, o, u, a;
            var f = 0;
            e = Base64._utf8_encode(e);
            while (f < e.length) {
                n = e.charCodeAt(f++);
                r = e.charCodeAt(f++);
                i = e.charCodeAt(f++);
                s = n >> 2;
                o = (n & 3) << 4 | r >> 4;
                u = (r & 15) << 2 | i >> 6;
                a = i & 63;
                if (isNaN(r)) {
                    u = a = 64
                } else if (isNaN(i)) {
                    a = 64
                }
                t = t + this._keyStr.charAt(s) + this._keyStr.charAt(o) + this._keyStr.charAt(u) + this._keyStr.charAt(a)
            }
            return t
        },
        decode: function (e) {
            var t = "";
            var n, r, i;
            var s, o, u, a;
            var f = 0;
            e = e.replace(/[^A-Za-z0-9+/=]/g, "");
            while (f < e.length) {
                s = this._keyStr.indexOf(e.charAt(f++));
                o = this._keyStr.indexOf(e.charAt(f++));
                u = this._keyStr.indexOf(e.charAt(f++));
                a = this._keyStr.indexOf(e.charAt(f++));
                n = s << 2 | o >> 4;
                r = (o & 15) << 4 | u >> 2;
                i = (u & 3) << 6 | a;
                t = t + String.fromCharCode(n);
                if (u != 64) {
                    t = t + String.fromCharCode(r)
                }
                if (a != 64) {
                    t = t + String.fromCharCode(i)
                }
            }
            t = Base64._utf8_decode(t);
            return t
        },
        _utf8_encode: function (e) {
            e = e.replace(/rn/g, "n");
            var t = "";
            for (var n = 0; n < e.length; n++) {
                var r = e.charCodeAt(n);
                if (r < 128) {
                    t += String.fromCharCode(r)
                } else if (r > 127 && r < 2048) {
                    t += String.fromCharCode(r >> 6 | 192);
                    t += String.fromCharCode(r & 63 | 128)
                } else {
                    t += String.fromCharCode(r >> 12 | 224);
                    t += String.fromCharCode(r >> 6 & 63 | 128);
                    t += String.fromCharCode(r & 63 | 128)
                }
            }
            return t
        },
        _utf8_decode: function (e) {
            var t = "";
            var n = 0;
            var r = c1 = c2 = 0;
            while (n < e.length) {
                r = e.charCodeAt(n);
                if (r < 128) {
                    t += String.fromCharCode(r);
                    n++
                } else if (r > 191 && r < 224) {
                    c2 = e.charCodeAt(n + 1);
                    t += String.fromCharCode((r & 31) << 6 | c2 & 63);
                    n += 2
                } else {
                    c2 = e.charCodeAt(n + 1);
                    c3 = e.charCodeAt(n + 2);
                    t += String.fromCharCode((r & 15) << 12 | (c2 & 63) << 6 | c3 & 63);
                    n += 3
                }
            }
            return t
        }
    }

    ,locationProtocol=location.protocol

    ,locationProtocol='http:'    //本地调试时打开,更新到服务器时注释

,locationHost="116.62.204.155",
    // ,locationHost="www.jiedaijia.cn",

    //, locationHost="192.168.1.100:8081"

//初始化

//locationHost=location.host,//若是本地调试，注释该行

    geturlBase = locationProtocol+"//"+locationHost+"/creditWell/",
    geturlimg = geturlBase,
    geturl = geturlBase+"product/",
    geturluser =  geturlBase+"user/",
    community = geturlBase+"community/",
    getsystem = geturlBase+"system/";

/*下载*/


function jiedaijiaDown(urlIos,urlAndroid_WeiXin,urlIos_WeiXin){

    var u = navigator.userAgent;

    var ua = navigator.userAgent.toLowerCase();

    var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1; //android终端
    var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端

    var isWeixin = ua.indexOf('micromessenger') != -1;

    if(isWeixin){

        if(isiOS){
            window.location.href=urlIos_WeiXin;
            return
        }
        if(isAndroid){
            window.location.href=urlAndroid_WeiXin;
            return
        }

    }else {

        if(isiOS){
            window.location.href=urlIos;
            return
        }else {

            //安卓，唤醒
            //安卓打开协议
            var src='jiedaijia://';
            openApp_(src);
        }



    }

    function openApp_(openUrl) {

        var down=function (opened) {

            if(opened==0){

                $.ajax({
                    url:geturl+'getShareUrl',
                    type:'get',
                    success:function(data){
                        var down=data.data.shareUrl[0].content;
                        var ifr = document.createElement('iframe');
                        ifr.src =geturlBase+down;
                        ifr.style.display = 'none';
                        document.body.appendChild(ifr);
                        setTimeout(function(){
                            document.body.removeChild(ifr);
                        }, 3000);
                    }
                });

            }

        };

        //检查app是否打开
        function checkOpen(down){
            var _clickTime = +(new Date());
            function check(elsTime) {
                if ( elsTime > 4000 || document.hidden || document.webkitHidden) {
                    down(1);
                } else {
                    down(0);
                }
            }
            //启动间隔20ms运行的定时器，并检测累计消耗时间是否超过3000ms，超过则结束
            var _count = 0, intHandle;
            intHandle = setInterval(function(){
                _count++;
                var elsTime = +(new Date()) - _clickTime;
                if (_count>=100 || elsTime > 4000 ) {
                    clearInterval(intHandle);
                    check(elsTime);
                }
            }, 30);
        }

        //在iframe 中打开APP
        var ifr = document.createElement('iframe');
        ifr.src = openUrl;
        ifr.style.display = 'none';

        checkOpen(down);

        document.body.appendChild(ifr);
        setTimeout(function() {
            document.body.removeChild(ifr);
        }, 3000);


    };

}



$('.downApk').click(function() {

    var urlIos_WeiXin="http://a.app.qq.com/o/simple.jsp?pkgname=com.dongxiangtech.jiedaijia";//微信里面的ios   可以直接放app store链接
    var urlAndroid_WeiXin="http://a.app.qq.com/o/simple.jsp?pkgname=com.dongxiangtech.jiedaijia";//微信里面的安卓  安卓应用宝链接

    var urlIos="https://itunes.apple.com/us/app/id1345892976";               //非微信里面的iso

    jiedaijiaDown(urlIos,urlAndroid_WeiXin,urlIos_WeiXin)


});



//微信，ios 安卓 打开app 用在借贷家，4个主页面，弹跳小窗下载。
function otherDownApk() {

    var u = navigator.userAgent;

    var ua = navigator.userAgent.toLowerCase();

    var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1; //android终端
    var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端

    var isWeixin = ua.indexOf('micromessenger') != -1;

    //是否是在微信里面打开，走应用宝，自动唤醒。
    if (isWeixin) {

        window.location.href='http://a.app.qq.com/o/simple.jsp?pkgname=com.dongxiangtech.jiedaijia';


    }else{

        //苹果走app store
        if(isiOS){
            window.location.href='https://itunes.apple.com/us/app/id1345892976';
        }else {

            //安卓，唤醒

            var src='jiedaijia://';

            //openApp(src);
            openApp_(src);



        }

    }

}

////微信，ios 安卓 打开app 用在借贷家，4个主页面，弹跳小窗下载。

function openApp_(openUrl) {

    var down=function (opened) {

        if(opened==0){

            myAjaxFunc({
                url:geturl+'getShareUrl',
                type:'get',
                mySuccess:function(data){
                    var down=data.data.shareUrl[0].content;
                    var ifr = document.createElement('iframe');
                    ifr.src =geturlBase+down;
                    ifr.style.display = 'none';
                    document.body.appendChild(ifr);
                    setTimeout(function(){
                        document.body.removeChild(ifr);
                    }, 3000);
                }
            });

        }


    };

    //检查app是否打开
    function checkOpen( down){
        var _clickTime = +(new Date());
        function check(elsTime) {
            if ( elsTime > 4000 || document.hidden || document.webkitHidden) {
                down(1);
            } else {
                down(0);
            }
        }
        //启动间隔20ms运行的定时器，并检测累计消耗时间是否超过3000ms，超过则结束
        var _count = 0, intHandle;
        intHandle = setInterval(function(){
            _count++;
            var elsTime = +(new Date()) - _clickTime;
            if (_count>=100 || elsTime > 4000 ) {
                clearInterval(intHandle);
                check(elsTime);
            }
        }, 30);
    }

    //在iframe 中打开APP
    var ifr = document.createElement('iframe');
    ifr.src = openUrl;
    ifr.style.display = 'none';

    checkOpen(down);

    document.body.appendChild(ifr);
    setTimeout(function() {
        document.body.removeChild(ifr);
    }, 3000);


};


function imgUpFile(formData) {
    var SystemDataimg = '';
    myAjaxFunc({
        url: getsystem + 'uploadFile',
        data: formData,
        type: "post",
        dataType: 'json',
        cache: false,
        async: false,
        processData: false,
        contentType: false,
        mySuccess: function (data) {
            if (isResponseSuccess('success', data)) {
                SystemDataimg = data.data.fileUrl
            } else {
                var msg = '图片上传失败';
                defaultHint(msg)
            }
        }
    });
    return SystemDataimg
}




//拍拍贷。安卓唤醒借贷家
function oppenApp_1(){
    var u = navigator.userAgent;

    var ua = navigator.userAgent.toLowerCase();

    var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1; //android终端
    var isWeixin = ua.indexOf('micromessenger') != -1;

    if(!isWeixin){

        if(isAndroid){

            var M={};

            if(M.Hint){
                return M.Hint.show();
            }

            setTimeout(function () {
                //安卓，唤醒
                //在iframe 中打开APP

                var ifr = document.createElement('iframe');
                ifr.src = 'jiedaijia://';
                ifr.style.display = 'none';
                document.body.appendChild(ifr);
                window.setTimeout(function(){
                    document.body.removeChild(ifr);
                },3000);

            },0)

        }
    }

}



//拍拍贷 下载，第三方推广点击下载
function getApk(){


    var urlIos_WeiXin="http://a.app.qq.com/o/simple.jsp?pkgname=com.dongxiangtech.jiedaijia";//微信里面的ios   可以直接放app store链接
    var urlAndroid_WeiXin="http://a.app.qq.com/o/simple.jsp?pkgname=com.dongxiangtech.jiedaijia"; //微信里面的安卓  安卓应用宝链接

    var urlIos="https://itunes.apple.com/us/app/id1345892976";               //非微信里面的iso

    jiedaijiaDown(urlIos,urlAndroid_WeiXin,urlIos_WeiXin)


}





var getSettingPicToken=function(){
    myAjaxFunc({
        url:getsystem+'getPicTokenSetting',
        type:'get',
        mySuccess:function (resp) {
            sessionStorage.setItem('picTokenAppId',resp.data.data);

        }
    });
};




function CurentTime() {
    var now = new Date();

    var year = now.getFullYear();       //年
    var month = now.getMonth() + 1;     //月
    var day = now.getDate();            //日

    var hh = now.getHours();            //时
    var mm = now.getMinutes();          //分

    var clock = year + "-";

    if(month < 10)
        clock += "0";

    clock += month + "-";

    if(day < 10)
        clock += "0";

    clock += day + " ";

    if(hh < 10)
        clock += "0";

    clock += hh + ":";
    if (mm < 10) clock += '0';

    clock += mm;


    return(clock);
}


function getday_(s1,s2){

    var days = s2.getTime() - s1.getTime();

    var time = parseInt(days / (1000 * 60 * 60 * 24));

    return time
}

//change by jack

var channelRequest = new searchUrl();
var myChannel=channelRequest.channel;

if(notNull(myChannel)){
    sessionStorage.setItem('channel', myChannel);
}
//change by jack



$("input").bind('input propertychange',function () {
    var lengthSt=$(this).attr("maxlength");
    if(!isNull(lengthSt)){
        var length=parseInt(lengthSt);
        var value=$(this).val();
        if(value.length>length)
            $(this).val(value.slice(0,length));
    }
});

function Page(opt) {
    var set = $.extend({num: null, startnum: 1, elem: null, callback: null}, opt || {});
    if (set.startnum > set.num || set.startnum < 1) {
        set.startnum = 1;
    }
    var n = 0, htm = '';
    var clickpages = {
        elem: set.elem,
        num: set.num,
        callback: set.callback,
        init: function () {
            this.elem.next('div.pageJump').children('.button').unbind('click')
            this.JumpPages();
            this.elem.children('li').click(function () {
                var txt = $(this).children('a').text();
                var page = '', ele = null;
                var page1 = parseInt(clickpages.elem.children('li.active').attr('page'));
                if (isNaN(parseInt(txt))) {
                    switch (txt) {
                        case '下一页':
                            if (page1 == clickpages.num) {
                                return;
                            }
                            if (page1 >= (clickpages.num - 2) || clickpages.num <= 6 || page1 < 3) {
                                ele = clickpages.elem.children('li.active').next();
                            } else {
                                clickpages.newPages('next', page1 + 1);
                                ele = clickpages.elem.children('li.active');
                            }
                            break;
                        case '上一页':
                            if (page1 == '1') {
                                return;
                            }
                            if (page1 >= (clickpages.num - 1) || page1 <= 3 || clickpages.num <= 6) {
                                ele = clickpages.elem.children('li.active').prev();
                            } else {
                                clickpages.newPages('prev', page1 - 1);
                                ele = clickpages.elem.children('li.active');
                            }
                            break;
                        case '«':
                            if (page1 == '1') {
                                return;
                            }
                            if (clickpages.num > 6) {
                                clickpages.newPages('«', 1);
                            }
                            ele = clickpages.elem.children('li[page=1]');
                            break;
                        case '»':
                            if (page1 == clickpages.num) {
                                return;
                            }
                            if (clickpages.num > 6) {
                                clickpages.newPages('»', clickpages.num);
                            }
                            ele = clickpages.elem.children('li[page=' + clickpages.num + ']');
                            break;
                        case '...':
                            return;
                    }
                } else {
                    if ((parseInt(txt) >= (clickpages.num - 3) || parseInt(txt) <= 3) && clickpages.num > 6) {
                        clickpages.newPages('jump', parseInt(txt));
                    }
                    ele = $(this);
                }
                page = clickpages.actPages(ele);
                if (page != '' && page != page1) {
                    if (clickpages.callback) {
                        clickpages.callback(parseInt(page));
                    }
                }
            });
        },
        //active
        actPages: function (ele) {
            ele.addClass('active').siblings().removeClass('active');
            return clickpages.elem.children('li.active').text();
        },
        JumpPages: function () {
            this.elem.next('div.pageJump').children('.button').click(function () {
                var i = parseInt($(this).siblings('input').val());
                if (isNaN(i) || (i <= 0) || i > clickpages.num) {
                    return;
                } else if (clickpages.num > 6) {
                    clickpages.newPages('jump', i);
                } else {
                    var ele = clickpages.elem.children('li[page=' + i + ']');
                    clickpages.actPages(ele);
                    if (clickpages.callback) {
                        clickpages.callback(i);
                    }
                    return;
                }

                if (clickpages.callback) {
                    clickpages.callback(i);
                }
            })
        },

        //newpages
        newPages: function (type, i) {
            var html = "", htmlLeft = "", htmlRight = "", htmlC = "";
            var HL = '<li><a>...</a></li>';
            html = '<li><a  aria-label="Previous">&laquo;</a></li>\
					<li><a>上一页</a></li>'
            for (var n = 0; n < 3; n++) {
                htmlC += '<li ' + ((n - 1) == 0 ? 'class="active"' : '') + ' page="' + (i + n - 1) + '"><a>' + (i + n - 1) + '</a></li>';
                htmlLeft += '<li ' + ((n + 2) == i ? 'class="active"' : '') + ' page="' + (n + 2) + '"><a>' + (n + 2) + '</a></li>';
                htmlRight += '<li ' + ((set.num + n - 3) == i ? 'class="active"' : '') + ' page="' + (set.num + n - 3) + '"><a>' + (set.num + n - 3) + '</a></li>';
            }

            switch (type) {
                case "next":
                    if (i <= 4) {
                        html += '<li page="1"><a>1</a></li>' + htmlLeft + HL + '<li page="' + set.num + '"><a>' + set.num + '</a></li>';
                    } else if (i >= (set.num - 3)) {
                        html += '<li page="1"><a>1</a></li>' + HL + htmlRight + '<li page="' + set.num + '"><a>' + set.num + '</a></li>';
                    } else {
                        html += '<li page="1"><a>1</a></li>' + HL + htmlC + HL + '<li page="' + set.num + '"><a>' + set.num + '</a></li>';
                    }
                    break;
                case "prev":
                    if (i <= 4) {
                        html += '<li page="1"><a>1</a></li>' + htmlLeft + HL + '<li page="' + set.num + '"><a>' + set.num + '</a></li>';
                    } else if (i >= (set.num - 3)) {
                        html += '<li page="1"><a>1</a></li>' + HL + htmlRight + '<li page="' + set.num + '"><a>' + set.num + '</a></li>';
                    } else {
                        html += '<li page="1"><a>1</a></li>' + HL + htmlC + HL + '<li page="' + set.num + '"><a>' + set.num + '</a></li>';
                    }
                    break;
                case "«" :
                    html += '<li class="active" page="1"><a>1</a></li>' + htmlLeft + HL + '<li page="' + set.num + '"><a>' + set.num + '</a></li>';
                    break;
                case "»" :
                    html += '<li page="1"><a>1</a></li>' + HL + htmlRight + '<li class="active" page="' + set.num + '"><a>' + set.num + '</a></li>';
                    break;
                case "jump" :
                    if (i <= 4) {
                        if (i == 1) {
                            html += '<li class="active" page="1"><a>1</a></li>' + htmlLeft + HL + '<li page="' + set.num + '"><a>' + set.num + '</a></li>';
                        } else {
                            html += '<li page="1"><a>1</a></li>' + htmlLeft + HL + '<li page="' + set.num + '"><a>' + set.num + '</a></li>';
                        }
                    } else if ((i >= set.num - 3) && (set.num >= 7)) {
                        if (i == set.num) {
                            html += '<li page="1"><a>1</a></li>' + HL + htmlRight + '<li class="active" page="' + set.num + '"><a>' + set.num + '</a></li>';
                        } else {
                            html += '<li page="1"><a>1</a></li>' + HL + htmlRight + '<li page="' + set.num + '"><a>' + set.num + '</a></li>';
                        }
                    } else {
                        html += '<li page="1"><a>1</a></li>' + HL + htmlC + HL + '<li page="' + set.num + '"><a>' + set.num + '</a></li>';
                    }
            }
            html += '<li><a>下一页</a></li>\
					<li><a  aria-label="Next">&raquo;</a></li>';
            if (this.num > 5 || this.num < 3) {
                set.elem.html(html);
                clickpages.init({num: set.num, elem: set.elem, callback: set.callback});
            }
        }
    }
    if (set.num <= 1) {
        $(".pagination").html('');
        return;
    } else if (parseInt(set.num) <= 6) {
        n = parseInt(set.num);
        var html = '<li><a  aria-label="Previous">&laquo;</a></li>\
					<li><a>上一页</a></li>';
        for (var i = 1; i <= n; i++) {
            if (i == set.startnum) {
                html += '<li class="active" page="' + i + '"><a>' + i + '</a></li>';
            } else {
                html += '<li page="' + i + '"><a>' + i + '</a></li>';
            }
        }
        html += '<li><a>下一页</a></li>\
					<li><a  aria-label="Next">&raquo;</a></li>';
        set.elem.html(html);
        clickpages.init();
    } else {
        clickpages.newPages("jump", set.startnum)
    }
}





function getDistance(obj) {
    if (!obj instanceof jQuery) {
        obj = $(obj);
    }
    var distance = {};
    distance.top = (obj.offset().top - $(document).scrollTop());
    distance.bottom = ($(window).height() - distance.top - obj.outerHeight());
    distance.left = (obj.offset().left - $(document).scrollLeft());
    distance.right = ($(window).width() - distance.left - obj.outerWidth());
    return distance;
}

